const express = require('express');
const router = express.Router();
const pool = require('../db');



// 用户注册接口
router.post('/register', async (req, res) => {
    const { phone, user_name, password, email, account, sex } = req.body;
    const processedData = {
        phone: phone === undefined ? null : phone,
        user_name: user_name === undefined ? null : user_name,
        password: password === undefined ? null : password,
        email: email === undefined ? null : email,
        account: account === undefined ? null : account,
        sex: sex === undefined ? null : sex
    };
    
    // 简单验证
    if (!password || !account) {
        return res.status(200).json({ status: false, message: '请填写完整信息' })
    }

    if (sex !== 1 && sex !== 0 && sex !== null&&  sex !== undefined) {
        return res.status(200).json({ status: false, message: '性别填写错误' })
    }

    try {
        // 检查用户名是否已存在
        const [users] = await pool.execute('SELECT * FROM user WHERE account = ?', [account]);
        if (users.length > 0) {
            return res.status(200).json({ status: false, message: '账号已存在' });
        }
        // 插入新用户
        await pool.execute(
            'INSERT INTO user ( phone, user_name, password, email, account, sex) VALUES (?, ?, ?, ?, ?, ?)',
            [ processedData.phone, processedData.user_name, processedData.password, processedData.email, processedData.account, processedData.sex ]
        );
        res.status(200).json({ status: true, message: '注册成功' });
    } catch (error) {
        console.error(error);
        res.status(200).json({ status: false, message: '服务器错误' });
    }
});

// 用户登录接口
router.post('/login', async (req, res) => {
    const { account, password } = req.body;
    
    // 简单验证
    if (!account || !password) {
        return res.status(200).json({ status: false, message: '请填写账号和密码' });
    }

    try {
        // 检查账号是否存在
        const [users] = await pool.execute('SELECT * FROM user WHERE account = ?', [account]);
        if (users.length === 0) {
            return res.status(200).json({ status: false, message: '账号不存在' });
        }
        
        // 验证密码
        const user = users[0];
        if (user.password !== password) {
            return res.status(200).json({ status: false, message: '密码错误' });
        }
        
        // 使用JWT生成token
        const jwt = require('jsonwebtoken');
        const {secret} = require("../secret")
        const token = jwt.sign(
            {
                user,
                exp: Math.floor(Date.now() / 1000) + (4*24*60 * 60) // 4天过期
            },
            secret // 实际项目中应使用环境变量存储密钥
        );
        
        res.status(200).json({ 
            status: true, 
            message: '登录成功',
            data: {
                token:'Bearer '+ token,
                user,
            }
        });
    } catch (error) {
        console.error(error);
        res.status(200).json({ status: false, message: '服务器错误' });
    }
});

module.exports = router;